package com.example.customviewtouch.downfresh.view

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView
import com.example.customviewtouch.downfresh.adapter.RefreshHeaderAdapter
import com.example.customviewtouch.downfresh.interfaces.IRefreshHeader
import com.example.customviewtouch.downfresh.interfaces.OnRefreshListener

class RefreshHeaderRecyclerView(context: Context, attrs: AttributeSet?) :
    RecyclerView(context, attrs) {

    private var mRefreshing = false
    private var adapter: RefreshHeaderAdapter? = null
    private var refreshHeader: IRefreshHeader? = null
    private var mRefreshListener: OnRefreshListener? = null

    private var mLastY = -1f
    private var sumOffSet = 0f

    fun setRefreshHeaderAdapter(adapter: RefreshHeaderAdapter) {
        if (this.adapter == null) {
            this.adapter = adapter
            refreshHeader = ArrowRefreshHeader(context.applicationContext)
            adapter.setRefreshHeader(refreshHeader)

        }
        super.setAdapter(adapter)
    }

    fun setOnRefreshListener(listener: OnRefreshListener) {
        if (mRefreshListener == null) {
            this.mRefreshListener = listener
        }
    }

    override fun onTouchEvent(e: MotionEvent): Boolean {
        if (mLastY == -1f) {
            mLastY = e.rawY
        }

        when(e.action) {
            MotionEvent.ACTION_DOWN -> {
                mLastY = e.rawY
                sumOffSet = 0f
            }

            MotionEvent.ACTION_MOVE -> {
                val deltaY = (e.rawY - mLastY) / 2
                mLastY = e.rawY
                sumOffSet += deltaY
                if (isOnTop() && !mRefreshing) {
                    refreshHeader?.onMove(deltaY, sumOffSet)
                    val headerVisibleHeight = refreshHeader?.getHeaderVisibleHeight()!!
                    Log.d("ZZZyt", "headerVisibleHeight = $headerVisibleHeight")
                    if (headerVisibleHeight > 0) {
                        return false
                    }
                }
            }

            else -> {
                mLastY = -1f
                if (isOnTop() && !mRefreshing) {
                    if (refreshHeader?.onRelease() == true) {
                        Log.d("ZZZyt","mRefreshListener != null")
                        if (mRefreshListener != null) {
                            Log.d("ZZZyt","mRefreshListener != null")
                            mRefreshing = true
                            mRefreshListener!!.onRefresh()
                        }
                    }
                }
            }
        }
        return super.onTouchEvent(e)
    }

    private fun isOnTop() :Boolean {
        return refreshHeader?.getHeadView()?.parent != null
    }

    fun refreshComplete() {
        if (mRefreshing) {
            mRefreshing = false
            refreshHeader?.refreshComplete()
        }
    }
}